Page({
  data: {
    theme: '',
    devices: [],
    zt: false,
    showunknown: false,
    deviceid: '',
    scanfrequency: 'medium',
    scanfrequencywz: '中',
    value: 1,
    array: ['低', '中', '高'],
    onemeterrssi: '-59',
    shzs: '2.7'
  },
  onShow() {
    this.setData({
      theme: wx.getAppBaseInfo().theme
    })
  },
  onShareAppMessage() {
    return {
      title: '蓝牙寻物'
    }
  },
  picker(e) {
    var t = e.detail.value
    if (t == 0) {
      this.setData({
        scanfrequency: 'low',
        scanfrequencywz: '低',
        value: 0
      })
    }
    if (t == 1) {
      this.setData({
        scanfrequency: 'medium',
        scanfrequencywz: '中',
        value: 1
      })
    }
    if (t == 2) {
      this.setData({
        scanfrequency: 'high',
        scanfrequencywz: '高',
        value: 2
      })
    }
  },
  startsearch() {
    var that = this
    if (!that.data.onemeterrssi || isNaN(that.data.onemeterrssi)) {
      wx.showToast({
        title: '1米RSSI不合法',
        icon: 'none'
      })
      return
    }
    if (!that.data.shzs || isNaN(that.data.shzs)) {
      wx.showToast({
        title: '损耗指数不合法',
        icon: 'none'
      })
      return
    }
    if (!wx.getSystemSetting().bluetoothEnabled) {
      wx.showModal({
        title: '提示',
        content: '请开启蓝牙',
        success(res) {
          if (res.confirm) {
            wx.openSystemBluetoothSetting()
          }
        }
      })
      return
    }
    if (wx.getAppAuthorizeSetting().bluetoothAuthorized != 'authorized') {
      wx.showModal({
        title: '提示',
        content: '请授权微信使用蓝牙',
        success(res) {
          if (res.confirm) {
            wx.openAppAuthorizeSetting()
          }
        }
      })
      return
    }
    if (wx.getStorageSync('qxsetting').bluetootha != true) {
      wx.showModal({
        title: '提示',
        content: '“蓝牙”权限的“蓝牙寻物”场景未开启，无法使用此功能。如需使用此功能，请点击“确定”进入权限管理页面开启“蓝牙”权限的“蓝牙寻物”场景。',
        success(res) {
          if (res.confirm) {
            that.router.navigateTo({
              url: '../qxgl/qxgl'
            })
          }
        }
      })
      return
    }
    wx.openBluetoothAdapter({
      success() {
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: true,
          powerLevel: that.data.scanfrequency,
          success() {
            that.setData({
              zt: true
            })
            wx.showToast({
              title: '已开始'
            })
            wx.onBluetoothDeviceFound(function () {
              wx.getBluetoothDevices({
                success(res) {
                  that.setData({
                    devices: res.devices.map(item => ({
                      ...item,
                      distance: Math.pow(10, ((Number(that.data.onemeterrssi) - item.RSSI) / (Number(that.data.shzs) * 10))).toFixed(1)
                    }))
                  })
                }
              })
            })
          }
        })
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '无法开始，错误信息：' + res.errMsg + '（errCode：' + res.errCode + '，errno：' + res.errno + '）',
          showCancel: false
        })
      }
    })
  },
  endsearch() {
    var that = this
    wx.offBluetoothDeviceFound()
    wx.stopBluetoothDevicesDiscovery({
      success() {
        wx.closeBluetoothAdapter({
          success() {
            that.setData({
              devices: [],
              zt: false,
              deviceid: ''
            })
            wx.showToast({
              title: '已结束'
            })
          }
        })
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: '无法结束，错误信息：' + res.errMsg + '（errCode：' + res.errCode + '，errno：' + res.errno + '）',
          showCancel: false
        })
      }
    })
  },
  lock(e) {
    var deviceid = e.currentTarget.dataset.deviceid
    this.setData({
      deviceid: deviceid
    })
  },
  unlock() {
    this.setData({
      deviceid: ''
    })
  }
})